<?php
/**
 * @copyright Copyright (c) 2015 VIKAA
 */

namespace app\services;

use app\components\Service;
use app\exception\ErrorCode;
use app\models\Authorize;
use app\models\User;
use yii\base\Exception;
use yii\helpers\ArrayHelper;


/**
 * 推送服务
 * Class PushService
 * @package app\services
 */
class AuthService extends Service
{
    /**
     * @param string $className
     * @return self
     */
    public static function instance($className = __CLASS__)
    {
        if (empty(self::$_instance[$className])) {
            self::$_instance[$className] = new $className();
        }
        return self::$_instance[$className];
    }

    /**
     * 获取TOKEN
     * @author xialei <xialeistudio@gmail.com>
     * @param $uid
     * @return array
     * @throws Exception
     */
    public function getToken($uid)
    {
        /** @var User $user */
        $user = User::findOne($uid);
        if (empty($user)) {
            throw new Exception(\Yii::t('app', 'invalid user_id'), ErrorCode::USER_NOT_FOUND);
        }
        //已存在的token全部过期
        Authorize::updateAll(['expires_in' => time() - 10], 'user_id=:id', [':id' => $user->user_id]);
        //生成新token
        $authorize = new Authorize();
        do {
            $authorize->token = \Yii::$app->security->generateRandomString(10);
            $exists = Authorize::find()->where(['token' => $authorize->token])->exists();
        } while ($exists);
        $authorize->user_id = $user->user_id;
        $authorize->expires_in = time() + \Yii::$app->params['user_duration'];
        if (!$authorize->save()) {
            throw new Exception($this->getError($authorize), ErrorCode::ACTIVE_RECORD_ERROR);
        }

        return ArrayHelper::toArray($authorize, ['token', 'expires_in']);
    }
}